import Immutable from 'immutable'
import { userLogin } from '../../api/user';
import axios from '../../api/apiConfing';

export const types = {
    // GET: 'USER/GET',
    UPDATE: 'USER/UPDATE',
    DEL: 'USER/DELETE',
    ADD: 'USER/ADD'
}

const user = JSON.parse(localStorage.getItem('user'))

let jwt = user ? user.jwt : ''

axios.interceptors.request.use(config => {
    config.headers['Authorization'] = jwt
    return config
})

// let tokenInterceptor

// if (user)
//     setTokenInterceptor(user.jwt)

// function setTokenInterceptor(jwt) {
//     // unSetTokenInterceptor()
//     // tokenInterceptor = 
//     console.log(jwt)
//     axios.interceptors.request.use(config => {
//         config.headers['Authorization'] = jwt
//         return config
//     })
// }

// function unSetTokenInterceptor() {
//     // if(tokenInterceptor)
//     //     axios.interceptors.request.eject(tokenInterceptor)
//     axios.interceptors.request.use(config => {
//         config.headers['Authorization'] = ''
//         return config
//     })
// }

const initialState = Immutable.fromJS(user ? user : {
    id: -1,
    name: '游客'
})

export const actions = {
    // getUser: () => ({
    //     type: types.GET
    // }),
    updateUser: user => ({
        type: types.UPDATE,
        user
    }),
    login: user => (dispatch, getState) => {
        return new Promise((resolve, reject) => {
            userLogin(user).then(res => {
                let data = res.data
                if (data.code === 0) {
                    // user.name = data.data.name
                    let u = data.data
                    // setTokenInterceptor(u.jwt)
                    jwt = u.jwt
                    dispatch(actions.updateUser(u))
                    localStorage.setItem('user', JSON.stringify(u))
                    resolve(u)
                } else {
                    reject(data.msg)
                }
            })
        })
    },
    logout: () => ({
        type: types.DEL
    })
}

const reducer = (state = initialState, action = {}) => {
    switch (action.type) {
        case types.ADD:
            return Immutable.fromJS(action.user)

        // case types.GET:
        //     return state

        case types.UPDATE:
            return Immutable.fromJS(action.user)

        case types.DEL:
            localStorage.removeItem('user')
            // unSetTokenInterceptor()
            jwt = ''
            return state.set('id', -1)
    
        default:
            return state
    }
}

export default reducer
